package com.fowo.api.common.excel;

import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.read.listener.ModelBuildEventListener;
import com.fowo.api.common.util.SheetUtils;
import org.springframework.util.ReflectionUtils;
import org.springframework.util.StringUtils;

import java.util.Collections;
import java.util.Map;

/**
 * 提供国际化支持的 Excel 模型类处理
 * @param <T>
 */
public class LocaleModelBuildEventListener<T> extends ModelBuildEventListener {
    private final Class<T> modelClass;

    public LocaleModelBuildEventListener(Class<T> modelClass) {
        this.modelClass = modelClass;
    }

    @Override
    public void invokeHead(Map<Integer, ReadCellData<?>> cellDataMap, AnalysisContext context) {
        ReflectionUtils.doWithFields(modelClass, field -> {
            final LocalExcelProperty.List localExcelProperties = field.getAnnotation(LocalExcelProperty.List.class);
            final ExcelProperty excelProperty = field.getAnnotation(ExcelProperty.class);
            for(Map.Entry<Integer, ReadCellData<?>> entry : cellDataMap.entrySet()) {
                final String s = SheetUtils.trim(entry.getValue().getStringValue());
                if (StringUtils.hasText(s)) {
                    if(localExcelProperties != null) {
                        for(LocalExcelProperty localExcelProperty : localExcelProperties.value()) {
                            if (localExcelProperty.value()[0].equals(s)) {
                                context.readSheetHolder().getExcelReadHeadProperty().getHeadMap().put(
                                        entry.getKey(),
                                        new Head(entry.getValue().getColumnIndex(), field, field.getName(), Collections.singletonList(s), false, false)
                                );
                                return;
                            }
                        }
                    }
                    if (excelProperty != null && excelProperty.value()[0].equals(s)) {
                        context.readSheetHolder().getExcelReadHeadProperty().getHeadMap().put(
                                entry.getKey(),
                                new Head(entry.getValue().getColumnIndex(), field, field.getName(), Collections.singletonList(s), false, false)
                        );
                        return;
                    }
                }
            }
        });
        super.invokeHead(cellDataMap, context);
    }
}
